<template>
  <el-dialog
    class="device-add-plan-comp"
    title="设置设备计划"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :visible="visible"
    :width="$setRem(850)"
    :before-close="handleCancel">
    <el-form
      element-loading-custom-class="custom-load"
      :model="ruleForm"
      :rules="rules"
      label-suffix="："
      size="medium"
      ref="ruleForm"
      :label-width="$setRem(120)"
      class="rule-form"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="计划名称" prop="planName" required>
            <span class="detail-text" v-if="hasDetail || hasCheck">{{ ruleForm.planName || '' }}</span>
            <el-input
              v-else
              type="text"
              clearable
              placeholder="请输入计划名称"
              v-model="ruleForm.planName">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划编号" prop="planNo" required>
            <span class="detail-text" v-if="hasDetail || hasCheck">{{ ruleForm.planNo || '' }}</span>
            <el-input
              v-else
              type="text"
              placeholder="请输入计划编号"
              clearable
              v-model="ruleForm.planNo">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <div v-if="!hasDetail && !hasCheck" class="btns">
          <el-button
            size="small"
            type="primary"
            @click="handleDownLoad">模板下载</el-button>
          <el-button size="small" type="primary" :loading="importLoading" class="upload-file">
            <input class="file" ref="file" type="file" @change="handleImport" />导入
          </el-button>
          <el-button
            class="add-btn"
            @click="handleAdd"
            type="primary"
            size="small"
            icon="el-icon-plus">新增</el-button>
        </div>
        <el-table
          class="table-container"
          :data="tableData"
          element-loading-custom-class="custom-load"
          row-key="id">
          <el-table-column label="序号" type="index" width="120"></el-table-column>
          <el-table-column label="名称" prop="name"></el-table-column>
          <el-table-column label="型号" prop="model"></el-table-column>
          <el-table-column label="单位" prop="unit"></el-table-column>
          <el-table-column label="数量" prop="num"></el-table-column>
          <div class="empty-content" slot="empty">
            <i class="iconfont iconwushuju"></i>
            <p>暂无数据</p>
          </div>
        </el-table>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item v-if="hasCheck" label="是否同意" prop="agree" required>
            <el-switch
              v-model="ruleForm.agree"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item>
          <el-form-item v-else label="审核人员" prop="reviewUser" required>
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.reviewName || '' }}</span>
            <el-select
              v-else
              placeholder="请选择审核人员"
              clearable
              filterable
              v-model="ruleForm.reviewUser">
              <el-option
                v-for="v in userList"
                :label="v.userName"
                :value="v.uuid"
                :key="v.uuid">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上传时间" prop="createTime" required>
            <span class="detail-text" v-if="hasDetail || hasCheck">{{ ruleForm.createTime || '' }}</span>
            <el-date-picker
              v-else
              v-model="ruleForm.createTime"
              format="yyyy-MM-d"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择上传时间">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="hasDetail && ruleForm.reviewStatus === '3'">
          <el-form-item label="原因" prop="remark">
            <span class="detail-text">{{ruleForm.remark}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-else-if="!ruleForm.agree && hasCheck">
          <el-form-item label="说明原因" prop="remark">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入原因"
              v-model="ruleForm.remark">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog
      class="add-plan-table"
      title="设置设备计划"
      :close-on-click-modal="false"
      :append-to-body="true"
      :destroy-on-close="true"
      :visible="addVisible"
      :width="$setRem(500)"
      :before-close="beforeClose">
      <el-form
        element-loading-custom-class="custom-load"
        :model="addForm"
        :rules="addRules"
        size="medium"
        ref="addForm"
        :label-width="$setRem(100)"
        class="rule-form"
      >
        <el-form-item label="名称" prop="name" required>
          <el-input
            type="text"
            clearable
            placeholder="请输入名称"
            v-model="addForm.name">
          </el-input>
        </el-form-item>
        <el-form-item label="型号" prop="model" required>
          <el-input
            type="text"
            clearable
            placeholder="请输入型号"
            v-model="addForm.model">
          </el-input>
        </el-form-item>
        <el-form-item label="单位" prop="unit" required>
          <el-input
            type="text"
            clearable
            placeholder="请输入单位"
            v-model="addForm.unit">
          </el-input>
        </el-form-item>
        <el-form-item label="数量" prop="num" required>
          <el-input-number
            :min="0"
            clearable
            placeholder="请输入数量"
            v-model="addForm.num">
          </el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button size="medium" @click="addVisible = false">取 消</el-button>
      <el-button
        size="medium"
        type="primary"
        @click="hanldeSubmit">
        保 存
      </el-button>
    </span>
    </el-dialog>
    <span slot="footer" class="dialog-footer">
      <el-button
        size="medium"
        type="primary"
        v-if="!hasDetail"
        @click="hanldeSave('2')">
        提 交
      </el-button>
      <el-button
        size="medium"
        type="primary"
        v-if="!hasDetail && !hasCheck"
        @click="hanldeSave('1')">
        暂 存
      </el-button>
      <el-button size="medium" @click="handleCancel">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'add'
    },
    options: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      userList: [],
      tableData: [],
      importLoading: false,
      ruleForm: {
        id: '',
        planName: '',
        planNo: '',
        reviewUser: '',
        reviewName: '',
        reviewStatus: '',
        agree: true,
        remark: '',
        createTime: this.$moment().format('YYYY-MM-DD')
      },
      rules: {
        planName: [
          { required: true, message: '请输入计划名称' },
        ],
        planNo: [
          { required: true, message: '请输入计划编号' },
        ],
        reviewUser: [
          { required: true, message: '请选择审核人员' },
        ],
        createTime: [
          { required: true, message: '请选择上传时间' },
        ],
      },
      addVisible: false,
      addForm: {
        name: '',
        model: '',
        unit: '',
        num: ''
      },
      addRules: {
        name: [
          { required: true, message: '请输入名称' },
          { trigger: 'blur' },
        ],
        model: [
          { required: true, message: '请输入型号' },
          { trigger: 'blur' },
        ],
        unit: [
          { required: true, message: '请输入单位' },
          { trigger: 'blur' },
        ],
        num: [
          { required: true, message: '请输入数量' },
        ],
      },
      detailData: {}
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    userInfo() {
      return this.$store.state.userInfo;
    },
    hasEdit() {
      return this.type === 'edit';
    },
    hasDetail() {
      return this.type === 'detail';
    },
    hasCheck() {
      return this.type === 'check';
    }
  },
  watch: {
    options: {
      deep: true,
      handler(data) {
        if (data) {
          const keys = Object.keys(this.ruleForm);
          Object.keys(data).length && keys.forEach(key => {
            const value = data[key] || '';
            this.ruleForm[key] = key === 'agree' ? true : value;
          });
          this.tableData = data.machPlanDetails || [];
        }
      }
    },
    visible(val) {
      if (!val) {
        this.ruleForm = {
          id: '',
          planName: '',
          planNo: '',
          reviewUser: '',
          reviewName: '',
          reviewStatus: '',
          agree: true,
          remark: '',
          createTime: this.$moment().format('YYYY-MM-DD')
        };
        this.importLoading = false;
      }
    }
  },
  created() {
    this.getUserList();
  },
  methods: {
    /**
     * 获取用户列表数据
     */
    async getUserList() {
      const params = {
        pageFlag: false
      };
      const { success, data: {
        data
      }} = await this.$Model.getUserList(params);
      if (success && data) {
        this.userList = data.list || [];
      }
    },
    // 获取设备计划明细导入模板
    async handleDownLoad() {
      const params = {
        projectId: this.projectId
      };
      const { success, data: {
        msg
      }} = await this.$Model.getDevicePlanTmp(params);
      success && msg && window.open(this.$checkUrl(msg));
    },
    // 导入
    async handleImport(e) {
      const file = e.target.files && e.target.files[0];
      if (!file || this.importLoading) return;
      const fm = new FormData();
      fm.append('file', file);
      this.importLoading = true;
      const { success, data: {
        data
      }} = await this.$Model.uploadDeviceExcel(fm);
      this.$refs.file.value = '';
      this.importLoading = false;
      console.log('data', data);
      if (success && Array.isArray(data)) {
        this.tableData = [...this.tableData, ...data];
        this.$message.success('导入成功');
      }
    },
    handleAdd() {
      this.addForm = {
        name: '',
        model: '',
        unit: '',
        num: ''
      };
      this.addVisible = true;
    },
    beforeClose() {
      this.addVisible = false;
    },
    handleCancel() {
      this.$emit('cancel');
    },
    hanldeSubmit() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          this.tableData.push({ ...this.addForm });
          this.addVisible = false;
        }
      });
    },
    // 保存
    hanldeSave(status) {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const { userName, uuid } = this.userInfo;
          const { reviewUser, agree, reviewName } = this.ruleForm;
          const { createName, createUser } = this.options;
          const currentUser = this.userList.find(v => {
            return v.uuid === reviewUser;
          });
          const params = {
            machPlan: {
              ...this.ruleForm,
              projectId: this.projectId,
              // 1：暂存；2：审核中；3：回退；4：审核完成
              reviewStatus: !agree
                ? '3'
                : this.type === 'check' ? '4' : status,
              createName: createName || userName,
              createUser: createUser || uuid,
              reviewName: reviewName || currentUser.userName
            },
            machPlanDetails: this.tableData
          };
          this.$emit('submit', params);
        }
      });
    },
  }
};
</script>

<style scoped lang="scss">
  @import "../../../assets/styles/table";
  @import "../../../assets/styles/dialog";
  .device-add-plan-comp {
    .btns {
      margin: 10px 0;
      float: right;
    }
    .table-container {
      margin: 20px 0;
      /deep/ .el-table__body-wrapper {
        min-height: 150px;
        max-height: 300px;
        overflow-y: auto;
      }
    }
    .upload-file {
      position: relative;
      cursor: pointer;
      .file {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        opacity: 0;
        cursor: pointer;
      }
    }
  }
  .add-plan-table {
    /deep/ .el-form-item {
      .el-form-item__label {
        color: #fff;
      }
      .el-form-item__content {
        width: 300px;
      }
    }
  }
</style>
